import random
import redis
import threading
import time

# 将 0001 题生成的 200 个激活码（或者优惠券）保存到 **Redis** 非关系型数据库中。 
# 参考 https://www.jianshu.com/p/2639549bedc8

pool=redis.ConnectionPool(host='127.0.0.1',port=6379,decode_responses=True,db=0,max_connections=2)

def generate_code():
    return random.sample(['{:0>6}'.format(str(x)) for x in range(0,999999)],200)


def redis_connection():
    r=redis.Redis(host='127.0.0.1',port=6379,decode_responses=True,db=1)
    # print(r.mset({'foo':'bar','giao':'ge'},))
    # print(r.mget('foo','giao'))
    # r.setbit('num',7,1)
    # r.set('foo',123)
    # print(r.incr('foo'))
    # print(r.decr('foo'))
    # print(r.append('foo',456))
    # print(r.get('foo'))
    # r.hset("hash1", "k1", "1.0")
    # r.hset("hash1", "k2", "2")
    # print(r.hincrbyfloat('hash1','k1',amount=3.0))
    r.sadd('code',*generate_code())


def redis_connectionPool(): 
    r1=redis_test()
    r2=redis_test()
    r3=redis_test()
    r1.start()
    r2.start()
    r3.start()




class redis_test(threading.Thread):
    def run(self):
        print(self.name,'开始')
        try:
            r=redis.Redis(connection_pool=pool)
            # print(threading.get_native_id(),'我获取了连接，但是我不干活，我休息',sleep_time,'秒')
            # time.sleep(sleep_time)
            for i in range(0,100):
                r.get('foo')
        except redis.exceptions.ConnectionError as e:
            import traceback
            print(self.name,'redis:连接有问题:',e)
            traceback.print_exc()
        print(self.name,'结束')
        r.close


redis_connection()
# print(bin(ord('2')))

